import 'package:get_it/get_it.dart';
import '../services/database_helper.dart';
import '../repositories/period_repository_impl.dart';
import '../repositories/user_profile_repository_impl.dart';
import '../services/data_service.dart';
import '../services/error_handler.dart';
import '../services/period_service.dart';
import '../services/app_state_service.dart';
import '../services/prediction_service.dart';

final GetIt locator = GetIt.instance;

void setupServiceLocator() {
  if (!locator.isRegistered<DatabaseHelper>()) {
    locator.registerSingleton<DatabaseHelper>(DatabaseHelper.instance);
    locator.registerSingleton<ErrorHandler>(ErrorHandler());
    
    locator.registerLazySingleton(
      () => UserProfileRepositoryImpl(locator<DatabaseHelper>()),
    );
    locator.registerLazySingleton(
      () => PeriodRepositoryImpl(locator<DatabaseHelper>()),
    );
    
    locator.registerLazySingleton<DataService>(
      () => DataService(),
    );
    locator.registerLazySingleton<PeriodService>(() => PeriodService());
    locator.registerLazySingleton<PredictionService>(() => PredictionService());
    
    final appStateService = AppStateService();
    locator.registerLazySingleton<AppStateService>(() => appStateService);
  }
}

T get<T extends Object>() {
  try {
    if (!locator.isRegistered<T>()) {
      setupServiceLocator();
    }
    return locator<T>();
  } catch (e) {
    String typeName = T.toString();
    
    if (typeName == 'AppStateService') {
      try {
        if (!locator.isRegistered<AppStateService>(instanceName: 'AppStateservice')) {
          setupServiceLocator();
        }
        return locator.get<AppStateService>(instanceName: 'AppStateservice') as T;
      } catch (_) {
        throw Exception('服务 $T 未注册或初始化失败: $e');
      }
    }
    
    throw Exception('服务 $T 未注册或初始化失败: $e');
  }
}

class ServiceLocator {
  static final ServiceLocator _instance = ServiceLocator._internal();

  factory ServiceLocator() => _instance;

  ServiceLocator._internal() {
    setupServiceLocator();
  }

  T get<T extends Object>() {
    try {
      if (!locator.isRegistered<T>()) {
        setupServiceLocator();
      }
      return locator<T>();
    } catch (e) {
      String typeName = T.toString();
      if (typeName == 'AppStateService') {
        try {
          if (!locator.isRegistered<AppStateService>(instanceName: 'AppStateservice')) {
            setupServiceLocator();
          }
          return locator.get<AppStateService>(instanceName: 'AppStateservice') as T;
        } catch (_) {
          throw Exception('服务 $T 未注册或初始化失败: $e');
        }
      }
      throw Exception('服务 $T 未注册或初始化失败: $e');
    }
  }

  void reset() {
    locator.reset();
    setupServiceLocator();
  }
}